<template>
  <div class="register-container">
    <div class="register-box">
      <h2>用户注册</h2>
      <el-form :model="registerForm" :rules="rules" ref="registerFormRef">
        <!-- 用户名 -->
        <el-form-item prop="username">
          <el-input v-model="registerForm.username" placeholder="用户名">
            <template #prefix><el-icon><User /></el-icon></template>
          </el-input>
        </el-form-item>

        <!-- 手机号 -->
        <el-form-item prop="phoneNumber">
          <el-input v-model="registerForm.phoneNumber" placeholder="手机号">
            <template #prefix><el-icon><Iphone /></el-icon></template>
          </el-input>
        </el-form-item>

        <!-- 角色名称 -->
        <el-form-item prop="roleName">
          <el-input v-model="registerForm.roleName" placeholder="角色名称">
            <template #prefix><el-icon><User /></el-icon></template>
          </el-input>
        </el-form-item>

        <!-- 组名称 -->
        <el-form-item prop="groupName">
          <el-input v-model="registerForm.groupName" placeholder="组名称">
            <template #prefix><el-icon><User /></el-icon></template>
          </el-input>
        </el-form-item>

        <!-- 密码 -->
        <el-form-item prop="password">
          <el-input v-model="registerForm.password" type="password" placeholder="密码" show-password>
            <template #prefix><el-icon><Lock /></el-icon></template>
          </el-input>
        </el-form-item>

        <!-- 确认密码 -->
        <el-form-item prop="confirmPassword">
          <el-input v-model="registerForm.confirmPassword" type="password" placeholder="确认密码" show-password>
            <template #prefix><el-icon><Lock /></el-icon></template>
          </el-input>
        </el-form-item>

        <!-- 注册按钮 -->
        <el-form-item>
          <el-button type="primary" :loading="loading" @click="handleRegister" class="register-button">注册</el-button>
        </el-form-item>
      </el-form>

      <!-- 登录链接 -->
      <div class="login-link">
        已有账号？<router-link to="/login">返回登录</router-link>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock, Iphone } from '@element-plus/icons-vue'
import axios from 'axios'

export default {
  name: 'RegisterPage',
  components: {
    User,
    Lock,
    Iphone
  },
  setup() {
    const router = useRouter()
    const registerFormRef = ref(null)
    const loading = ref(false)

    const registerForm = reactive({
      username: '',
      phoneNumber: '',
      roleName: '',
      groupName: '', // 新增组名称字段
      password: '',
      confirmPassword: ''
    })

    // 自定义手机号校验规则
    const validatePhone = (rule, value, callback) => {
      const phoneRegex = /^1[3-9]\d{9}$/; // 中国大陆手机号格式
      if (!value) {
        callback(new Error('请输入手机号'))
      } else if (!phoneRegex.test(value)) {
        callback(new Error('手机号格式不正确'))
      } else {
        callback()
      }
    }

    // 密码校验规则
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== registerForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }

    // 表单验证规则
    const rules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
      ],
      phoneNumber: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { validator: validatePhone, trigger: 'blur' }
      ],
      roleName: [
        { required: true, message: '请输入角色名称', trigger: 'blur' },
        { min: 2, max: 20, message: '角色名称长度应在 2 到 20 个字符', trigger: 'blur' }
      ],
      groupName: [ // 新增组名称验证规则
        { required: true, message: '请输入组名称', trigger: 'blur' },
        { min: 2, max: 20, message: '组名称长度应在 2 到 20 个字符', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, message: '请再次输入密码', trigger: 'blur' },
        { validator: validatePass, trigger: 'blur' }
      ]
    }

    // 处理注册请求
    const handleRegister = async () => {
      try {
        const valid = await registerFormRef.value.validate()
        if (!valid) return

        loading.value = true
        const response = await axios.post('http://localhost:8080/auth/register', {
          username: registerForm.username,
          phoneNumber: registerForm.phoneNumber,
          roleName: registerForm.roleName,
          groupName: registerForm.groupName, // 新增组名称字段
          password: registerForm.password
        })

        if (response.data.startsWith("注册成功")) {
          const token = response.data.split("您的令牌是：")[1]; // 提取 JWT 令牌
          localStorage.setItem("token", token); // 存储到 localStorage

          ElMessage.success("注册成功，已自动登录");
          router.push("/dashboard"); // 直接跳转到用户首页
        } else {
          ElMessage.error(response.data || "注册失败");
        }
      } catch (error) {
        ElMessage.error(error.response?.data || "注册失败: 请稍后再试");
      } finally {
        loading.value = false;
      }
    }

    return {
      registerFormRef,
      loading,
      registerForm,
      rules,
      handleRegister
    }
  }
}
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f7fa;
}

.register-box {
  width: 400px;
  padding: 40px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

h2 {
  text-align: center;
  margin-bottom: 30px;
  color: #409EFF;
}

.register-button {
  width: 100%;
}

.login-link {
  text-align: center;
  margin-top: 20px;
  font-size: 14px;
}

.login-link a {
  color: #409EFF;
  text-decoration: none;
}
</style>